/**
 * Written By Nicholas Hillier Nov 2008
 */
package com.ghostmonk.net
{	
	import flash.display.*;
	import flash.events.*;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;

	public class ImageLoader extends Sprite
	{
		private var _loader:Loader;
		private var _callback:Function;
		private var _checkPolicyFlag:Boolean
		private var _errorCall:Function;
		
		private function set errorCall(call:Function):void
		{
			_errorCall = call; 
		}
		
		public function ImageLoader(checkPolicyFlag:Boolean = false)
		{
			_checkPolicyFlag = checkPolicyFlag;
			_loader = new Loader();
			_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
			addChild(_loader);
		}
		
		public function load(url:String, callBack:Function):void
		{
//			/_loader.unload();
			_callback = callBack;
			_loader.load(new URLRequest(url), new LoaderContext(_checkPolicyFlag));
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
		} 
		
		private function onComplete(e:Event):void
		{
			var bit:Bitmap = Bitmap(_loader.content);
			_callback(bit);
			bit.smoothing = true;
			_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onComplete);
		}
		
		private function onIOError(e:IOErrorEvent):void
		{
			if(_errorCall != null) _errorCall();
			_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onComplete);
		}
		
	}
}